<template>
  <div class="bank-transactions">
    <!-- 数据管理模式切换 -->
    <el-tabs v-model="viewMode" class="view-mode-tabs">
      <el-tab-pane label="业务模式" name="business">
        <!-- 业务模式内容 -->
        <!-- 页面标题 -->
        <PageHeader 
          title="银行流水" 
          description="管理银行流水记录，进行智能对账和批量操作"
          icon="Money"
        />
        
        <!-- 添加提示信息 -->
        <div class="data-management-tip" v-if="showDataManagementTip">
          <el-alert
            title="提示：此页面用于批量数据维护。如需进行日常业务操作，请切换到业务模式"
            type="info"
            show-icon
            closable
            @close="handleTipClose"
          >
            <template #default>
              <div class="tip-content">
                <span>提示：此页面用于批量数据维护。如需进行日常业务操作，请前往</span>
                <el-link type="primary" @click="goToReconciliation">智能对账 → 银行流水</el-link>
              </div>
            </template>
          </el-alert>
        </div>
        
        <!-- 智能洞察 -->
        <SmartInsights 
          v-if="stats && Object.keys(stats).length > 0"
          :insights="smartInsights"
          @action="handleInsightAction"
        />
        
        <!-- 银行流水统计 -->
        <!-- 功能区域 -->
        <el-card class="function-area" shadow="never">
          <el-row :gutter="20">
            <el-col :span="16">
              <!-- <TransactionFilter 
                :query-params="queryParams"
                @search="handleSearch"
                @reset="handleReset"
              /> -->
            </el-col>
            <el-col :span="8">
              <div class="function-buttons">
                <el-dropdown trigger="click" @command="handleBatchCommand">
                  <el-button class="batch-btn">
                    批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="export">导出流水</el-dropdown-item>
                      <el-dropdown-item command="import">导入流水</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除流水</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 银行流水表格 -->
        <!-- <TransactionTable
          :table-data="transactions"
          :loading="loading"
          :pagination="pagination"
          :selected-transactions="selectedTransactions"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="handleSortChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @command="handleTableCommand"
        /> -->
        
        <!-- 新增流水抽屉 -->
        <!-- <TransactionEditDrawer
          v-model="addDrawerVisible"
          :mode="'create'"
          :transaction-data="null"
          @submit="createTransaction"
          @close="handleAddDrawerClose"
        />
        
        <!-- 编辑流水抽屉 -->
        <TransactionEditDrawer
          v-model="editDrawerVisible"
          :mode="'edit'"
          :transaction-data="editingTransaction"
          @submit="updateTransaction"
          @close="handleEditDrawerClose"
        /> -->
        
        <!-- 流水详情抽屉 -->
        <!-- <TransactionDetailDrawer
          v-model="detailDrawerVisible"
          :transaction-id="detailTransaction?.id || null"
          @edit="handleEditTransaction"
          @close="handleDetailDrawerClose"
        /> -->
        
        <!-- 流水导入向导 -->
        <!-- <TransactionImportWizard
          v-model="importWizardVisible"
          :mode="'import'"
          :filter-params="queryParams"
          @import-success="handleImportSuccess"
        /> -->
      </el-tab-pane>
      <el-tab-pane label="数据管理模式" name="data">
        <!-- 数据管理模式内容 -->
        <el-card class="main-card">
          <!-- 页面头部 -->
          <TransactionHeader 
            :stats="stats"
            :loading="loading"
            :capturing="capturing"
            :selected-transactions="selectedTransactions"
            :view-mode="viewMode"
            :show-advanced-filter="showAdvancedFilter"
            @search="handleSearch"
            @reset="handleReset"
            @toggle-filter="showAdvancedFilter = !showAdvancedFilter"
            @view-mode-change="viewMode = $event"
            @showImportWizard="showImportDialog = true"
            @smart-filter="showFilterDialog = true"
            @show-batch-operations="showBatchDialog = true"
            @load-transactions="loadTransactions"
            @export-transactions="handleExportTransactions"
            @handle-smart-capture="handleSmartCapture"
          />
          
          <!-- 高级筛选 -->
          <TransactionFilterData 
            v-show="showAdvancedFilter"
            v-model="queryParams"
            @search="handleSearch"
            @reset="handleReset"
          />
          
          <!-- 智能建议 -->
          <SmartActions 
            v-if="showSmartActions"
            :smart-suggestions="smartSuggestions"
            :get-suggestion-type="getSuggestionType"
            @apply-suggestion="applySuggestion"
            @apply-all-suggestions="applyAllSuggestions"
            @remove-suggestion="removeSuggestion"
          />
          
          <!-- 智能提醒 -->
          <TransactionSmartAlerts 
            :transactions="tableData"
            @alert-click="handleAlertClick"
          />
          
          <!-- 交易表格 -->
          <TransactionTableData
            ref="transactionTableRef"
            v-model:query-params="queryParams"
            :table-data="tableData"
            :loading="loading"
            :pagination="{ page: queryParams.page, limit: queryParams.limit, total: total }"
            :selected-transactions="selectedTransactions"
            :show-advanced-filter="showAdvancedFilter"
            @selection-change="handleSelectionChange"
            @view-detail="handleViewTransactionDetail"
            @manual-match="handleManualMatch"
            @edit="handleEditTransactionRemark"
            @refresh="loadTransactions"
          />
          
          <!-- 分页 -->
          <TransactionPagination
            :model-value="{ page: queryParams.page, limit: queryParams.limit }"
            :total="total"
            @update:model-value="(val: { page: number; limit: number }) => { queryParams.page = val.page; queryParams.limit = val.limit }"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-card>
        
        <!-- 导入向导对话框 -->
        <TransactionImportWizardData 
          v-model="showImportDialog" 
          @import-success="handleImportSuccess"
        />
        
        <!-- 智能过滤设置抽屉 -->
        <SmartFilter 
          v-model="showFilterDialog" 
          @rules-updated="handleFilterRulesUpdated"
        />
        
        <!-- 批量操作面板 -->
        <BatchOperationPanel 
          v-model="showBatchDialog" 
          :selected-transactions="selectedTransactions"
          @batch-action="handleBatchAction"
        />
        
        <!-- 流水详情对话框 -->
        <TransactionDetail
          v-model="showTransactionDetailDialog"
          :transaction="currentTransaction"
          @edit="handleEditTransactionRemark"
        />
        
        <!-- 手动匹配抽屉 -->
        <ManualMatchDialog
          v-model="showManualMatchDialog"
          :transaction="currentTransaction"
          @match-success="handleMatchSuccess"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Money, Plus, ArrowDown, Upload, Download, Delete 
} from '@element-plus/icons-vue'
import * as transactionAPI from '@/api/transaction'
import { getTransactionStats } from '@/api/transaction'
import type { Transaction } from '@/types/transaction'

// 使用路由
const router = useRouter()

// 控制提示信息显示
const showDataManagementTip = ref(true)

// 视图模式
const viewMode = ref('business')

// 跳转到智能对账
const goToReconciliation = () => {
  router.push('/finance/reconciliation/workbench')
}

// 关闭提示信息
const handleTipClose = () => {
  showDataManagementTip.value = false
}

// 导入组件
import PageHeader from '@/components/layout/PageHeader.vue'
import SmartInsights from '@/components/insights/SmartInsights.vue'

// 数据管理模式组件
import TransactionFilterData from '@/views/finance/transactions-data-components/components/TransactionFilter.vue'
import TransactionTableData from '@/views/finance/transactions-data-components/components/TransactionTable.vue'
import TransactionDetail from '@/views/finance/transactions-data-components/components/TransactionDetail.vue'
import TransactionImportWizardData from '@/views/finance/transactions-data-components/components/TransactionImportWizard.vue'
import TransactionHeader from '@/views/finance/transactions-data-components/components/TransactionHeader.vue'
import TransactionPagination from '@/views/finance/transactions-data-components/components/TransactionPagination.vue'
import TransactionSmartAlerts from '@/views/finance/transactions-data-components/components/TransactionSmartAlerts.vue'
import SmartActions from '@/views/finance/transactions-data-components/components/SmartActions.vue'
import SmartFilter from '@/views/finance/transactions-data-components/components/SmartFilter.vue'
import BatchOperationPanel from '@/views/finance/transactions-data-components/components/BatchOperationPanel.vue'
import ManualMatchDialog from '@/views/finance/transactions-data-components/components/ManualMatchDialog.vue'

// 业务模式组件（使用数据管理模式组件作为替代）
import TransactionEditDrawer from '@/views/finance/transactions-data-components/components/TransactionImportWizard.vue'
import TransactionDetailDrawer from '@/views/finance/transactions-data-components/components/TransactionDetail.vue'
import TransactionImportWizard from '@/views/finance/transactions-data-components/components/TransactionImportWizard.vue'

interface TransactionQueryParams {
  transactionNo: string
  bankAccount: string
  transactionType: string
  status: string
  minAmount?: number
  maxAmount?: number
  transactionDateRange: string[]
  page: number
  limit: number
}

interface TransactionStats {
  totalTransactions: number
  incomeTransactions: number
  expenseTransactions: number
  unmatchedTransactions: number
  transactionTrend: number
  incomeTrend: number
  expenseTrend: number
}

// 数据管理模式相关数据
const capturing = ref(false)
const showAdvancedFilter = ref(false)
const smartSuggestions = ref<any[]>([])
const filterRules = ref<any[]>([])
const currentTransactionId = ref('')
const currentTransaction = ref<any>(null)
const showTransactionDetailDialog = ref(false)
const showManualMatchDialog = ref(false)
const showImportDialog = ref(false)
const showFilterDialog = ref(false)
const showBatchDialog = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)
const transactionTableRef = ref()

// 监听 showImportDialog 的变化
watch(showImportDialog, (newVal) => {
  console.log('showImportDialog changed to:', newVal)
})

// 计算属性
const showSmartActions = computed(() => smartSuggestions.value.length > 0)

// 响应式数据
const transactions = ref<Transaction[]>([])
const loading = ref(false)
const addDrawerVisible = ref(false)
const editDrawerVisible = ref(false)
const detailDrawerVisible = ref(false)
const importWizardVisible = ref(false)
const detailTransaction = ref<Transaction | null>(null)
const editingTransaction = ref<Transaction | null>(null)
const selectedTransactions = ref<Transaction[]>([])
const stats = ref<TransactionStats>({
  totalTransactions: 0,
  incomeTransactions: 0,
  expenseTransactions: 0,
  unmatchedTransactions: 0,
  transactionTrend: 0,
  incomeTrend: 0,
  expenseTrend: 0
})

// 查询参数
const queryParams = reactive<TransactionQueryParams>({
  transactionNo: '',
  bankAccount: '',
  transactionType: '',
  status: '',
  minAmount: undefined,
  maxAmount: undefined,
  transactionDateRange: [],
  page: 1,
  limit: 20
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 智能洞察
const smartInsights = computed(() => {
  return [
    {
      id: 'unmatched-transactions',
      title: '未匹配流水',
      content: `发现 ${stats.value.unmatchedTransactions} 笔未匹配的银行流水`,
      type: 'warning',
      actions: [
        { text: '立即处理', command: 'handle-unmatched' }
      ]
    },
    {
      id: 'high-amount-transactions',
      title: '大额流水',
      content: '检测到多笔大额流水，请关注资金流向',
      type: 'info',
      actions: [
        { text: '查看详情', command: 'view-high-amount' }
      ]
    }
  ]
})

// 方法
const loadTransactions = async () => {
  loading.value = true
  try {
    const response = await transactionAPI.getTransactions({
      ...queryParams,
      page: pagination.page,
      limit: pagination.limit
    })
    
    transactions.value = response.data.list
    pagination.total = response.data.total
    
    // 加载统计数据
    loadStats()
  } catch (error) {
    ElMessage.error('加载流水记录失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await getTransactionStats()
    if (response.success && response.data) {
      stats.value = response.data
    } else {
      // 如果API调用失败或返回空数据，使用默认值而不是null
      stats.value = {
        totalTransactions: 0,
        incomeTransactions: 0,
        expenseTransactions: 0,
        unmatchedTransactions: 0,
        transactionTrend: 0,
        incomeTrend: 0,
        expenseTrend: 0
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 如果发生错误，使用默认值而不是null
    stats.value = {
      totalTransactions: 0,
      incomeTransactions: 0,
      expenseTransactions: 0,
      unmatchedTransactions: 0,
      transactionTrend: 0,
      incomeTrend: 0,
      expenseTrend: 0
    }
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadTransactions()
}

const handleReset = () => {
  Object.assign(queryParams, {
    transactionNo: '',
    bankAccount: '',
    transactionType: '',
    status: '',
    minAmount: undefined,
    maxAmount: undefined,
    transactionDateRange: []
  })
  pagination.page = 1
  loadTransactions()
}

const handleSelectionChange = (selection: Transaction[]) => {
  selectedTransactions.value = selection
}

const handleRowClick = (row: Transaction) => {
  detailTransaction.value = row
  detailDrawerVisible.value = true
}

const handleSortChange = (sort: any) => {
  // 处理排序
  console.log('排序:', sort)
}

const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  loadTransactions()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadTransactions()
}

const handleTableCommand = (command: string, row: Transaction) => {
  switch (command) {
    case 'edit':
      handleRowClick(row)
      break
    case 'delete':
      handleDeleteTransaction(row)
      break
    case 'detail':
      detailTransaction.value = row
      detailDrawerVisible.value = true
      break
  }
}

const handleBatchCommand = (command: string) => {
  switch (command) {
    case 'export':
      handleExportTransactions()
      break
    case 'import':
      importWizardVisible.value = true
      break
    case 'delete':
      handleBatchDelete()
      break
  }
}

const handleExportTransactions = () => {
  // 处理导出
  ElMessage.info('导出功能开发中')
}

const handleImportSuccess = () => {
  loadTransactions()
  ElMessage.success('导入成功')
}

const createTransaction = async (data: any) => {
  try {
    await transactionAPI.createTransaction(data)
    addDrawerVisible.value = false
    loadTransactions()
    ElMessage.success('新增成功')
  } catch (error) {
    ElMessage.error('新增失败')
  }
}

const updateTransaction = async (data: any) => {
  try {
    await transactionAPI.updateTransaction(data.id, data)
    editDrawerVisible.value = false
    loadTransactions()
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const handleDeleteTransaction = async (row: Transaction) => {
  try {
    await ElMessageBox.confirm('确定要删除该流水记录吗？', '提示', {
      type: 'warning'
    })
    
    await transactionAPI.deleteTransaction(row.id)
    loadTransactions()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedTransactions.value.length === 0) {
    ElMessage.warning('请先选择要删除的流水记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedTransactions.value.length} 条流水记录吗？`, '提示', {
      type: 'warning'
    })
    
    const ids = selectedTransactions.value.map(item => item.id)
    await transactionAPI.batchDeleteTransactions(ids)
    loadTransactions()
    ElMessage.success('批量删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const handleAddDrawerClose = () => {
  addDrawerVisible.value = false
}

const handleEditDrawerClose = () => {
  editDrawerVisible.value = false
}

const handleDetailDrawerClose = () => {
  detailDrawerVisible.value = false
}

const handleEditTransaction = (transaction: Transaction) => {
  detailDrawerVisible.value = false
  editingTransaction.value = transaction
  editDrawerVisible.value = true
}

const handleInsightAction = (action: string, insight: any) => {
  switch (action) {
    case 'handle-unmatched':
      // 处理未匹配流水
      break
    case 'view-high-amount':
      // 查看大额流水
      break
  }
}

// 数据管理模式方法
const loadSmartSuggestions = async () => {
  // 模拟加载智能建议
  smartSuggestions.value = [
    {
      id: '1',
      type: 'filter',
      description: '建议过滤5条非业务相关流水',
      transactions: ['1', '2', '3', '4', '5'],
      confidence: 95
    },
    {
      id: '2',
      type: 'match',
      description: '建议匹配3条高置信度流水',
      transactions: ['6', '7', '8'],
      confidence: 88
    }
  ]
}

// 获取建议类型的方法
const getSuggestionType = (type: string) => {
  const typeMap: Record<string, string> = {
    filter: 'warning',
    match: 'success',
    duplicate: 'info'
  }
  return typeMap[type] || 'info'
}

// 应用所有建议
const applyAllSuggestions = () => {
  ElMessageBox.confirm('确定要应用所有智能建议吗？', '应用所有建议', {
    type: 'warning'
    }).then(() => {
    // 应用所有建议的逻辑
    ElMessage.success('所有建议已应用')
    // 重新加载数据
    loadTransactions()
  }).catch(() => {
    // 取消应用
  })
}

// 移除建议
const removeSuggestion = (suggestionId: string) => {
  smartSuggestions.value = smartSuggestions.value.filter((s: any) => s.id !== suggestionId)
}

const handlePageChange = (page: number) => {
  queryParams.page = page
  loadTransactions()
}

const handlePageSizeChange = (size: number) => {
  queryParams.limit = size
  queryParams.page = 1
  loadTransactions()
}

const applySuggestion = (suggestion: any) => {
  ElMessageBox.confirm(`确定要应用建议"${suggestion.description}"吗？`, '应用建议', {
    type: 'warning'
  }).then(() => {
    // 应用建议的逻辑
    ElMessage.success('建议已应用')
    // 重新加载数据
    loadTransactions()
  }).catch(() => {
    // 取消应用
  })
}

const handleViewTransactionDetail = (transaction: any) => {
  currentTransaction.value = transaction
  showTransactionDetailDialog.value = true
}

const handleEditTransactionRemark = (transaction: any) => {
  // 编辑备注的逻辑
  ElMessage.success('备注已更新')
}

const handleManualMatch = (transaction: any) => {
  currentTransaction.value = transaction
  showManualMatchDialog.value = true
}

const handleMatchSuccess = (transaction: any, order: any) => {
  ElMessage.success(`流水${transaction.transactionId}已成功匹配订单${order.orderId}`)
  // 重新加载数据
  loadTransactions()
}

const handleFilterRulesUpdated = (rules: any[]) => {
  filterRules.value = rules
  ElMessage.success('过滤规则已更新')
  // 重新加载数据
  loadTransactions()
}

const handleBatchAction = (action: string, data: any) => {
  ElMessage.success(`批量操作"${action}"执行成功`)
  // 重新加载数据
  loadTransactions()
}

const handleAlertClick = (alert: any) => {
  ElMessage.info(`处理提醒: ${alert.title}`)
  // 可以根据提醒类型执行不同的操作
  switch (alert.type) {
    case 'duplicate':
      // 筛选显示重复交易
      queryParams.showDuplicates = true
      handleSearch()
      break
    case 'largeAmount':
      // 可以跳转到大额交易筛选
      ElMessage.info('已筛选显示大额交易')
      break
    case 'abnormalTime':
      // 可以跳转到异常时间交易筛选
      ElMessage.info('已筛选显示异常时间交易')
      break
  }
}

const handleSmartCapture = () => {
  capturing.value = true
  // 智能抓取的逻辑
  setTimeout(() => {
    capturing.value = false
    ElMessage.success('智能抓取完成')
    // 重新加载数据
    loadTransactions()
  }, 2000)
}

// 生命周期
onMounted(() => {
  loadTransactions()
})
</script>

<style scoped lang="scss">
.bank-transactions {
  padding: 20px;
}

.data-management-tip {
  margin-bottom: 20px;
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.function-area {
  margin-bottom: 20px;
}

.function-buttons {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
}

.batch-btn {
  margin-left: 12px;
}

.main-card {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .bank-transactions {
    padding: 12px;
  }
  
  .function-area {
    margin-bottom: 16px;
  }
}
</style>